package cn.yusei.teamTribe.dao.post;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import cn.yusei.teamTribe.dao.post.po.PostPO;

@Mapper
public interface PostDAO {

	final String POST_TABLE = " e_post ";
	final String POST_USER_TEAM_TABLE = " r_post_user_team ";
	final String INSERT_FIELDS = " (title, content, target_id) ";
	final String INSERT_REFLECT_FIELDS = " (post_id, user_id, team_id) ";
	final String SELECT_FIELDS = " id, title, content, create_time, edit_time, target_id, com_cnt ";
	
	@Insert({
		"insert into", POST_TABLE, INSERT_FIELDS, "values (#{title}, #{content}, #{targetId});"
		})
	void insert(PostPO postPO);
	
	@Select({"select target_id from", POST_TABLE, "where id = #{id}"})
	public Integer selectTargetIdById(@Param("id") int id);
	
	@Select({"select exists (select * from", POST_TABLE, "where id = #{id} and deleted = 0 limit 1)"})
	public boolean exists(@Param("id") int id);
	
	@Select({"select", SELECT_FIELDS, "from", POST_TABLE, "where id = #{id} and deleted = 0 limit 1"})
	public PostPO selectById(@Param("id") int id);
	
	@Select({"select id from", POST_TABLE,
		"where id in (select post_id from", POST_USER_TEAM_TABLE, "where user_id = #{userId}) and target_id = 0 and deleted = 0 order by id desc limit #{offset}, #{num}"})
	public int[] selectByUserId(@Param("userId") int userId, @Param("offset") int offset, @Param("num") int num);
	
	@Select({"select id from", POST_TABLE,
		"where id in (select post_id from", POST_USER_TEAM_TABLE, "where target_id = #{targetId}) and deleted = 0 order by id desc limit #{offset}, #{num}"})
	public int[] selectByTargetId(@Param("targetId") int targetId, @Param("offset") int offset, @Param("num") int num);
	
	@Select({"select last_insert_id()"})
	public int selectLastInertId();
	
	@Update({"update", POST_TABLE, "set title = #{title}, content = #{content}, edit_time = now() where id = #{id}"})
	public void update(PostPO postPO);
	
	@Update({"update", POST_TABLE, "set deleted = 1 where id = #{id} or target_id = #{id}"})
	public void delete(int id);
	
	@Select({"select post_id from",POST_USER_TEAM_TABLE,",", POST_TABLE,
		"where team_id = #{teamId} and id = post_id and target_id = 0"})
	public int[] selectByTeamId(@Param("teamId")int teamId);
	
	@Select({"select post_id from",POST_USER_TEAM_TABLE, ", ", POST_TABLE,
		"where team_id = #{teamId} and id = post_id and target_id = 0 order by post_id desc limit #{offset}, #{num}"})
	public int[] selectByTeam(@Param("teamId")int teamId, @Param("offset")int offset, @Param("num") int num);
}
